import { Component } from 'react'
import './app.scss'
import global from './global'
import Taro from "@tarojs/taro";
import Request from "./api";
import Event from "./event";
import {View} from '@tarojs/components';
// eslint-disable-next-line import/first
// import 'taro-ui/dist/style/index.scss'

class App extends Component {

  async componentWillMount () {
    if (global.isLogin !== true) {
      await this.checkRegisterInfo();
    }
    await this.getSystemInfo();
    await this.checkOperationRemind();
    Event.emit('getSystemInfo', global);
    Event.on("updateSystemInfo", async currentBindingVillage => {
      // if (currentBindingVillage != )
      this.getSystemInfo(currentBindingVillage.villageId);
      await this.checkOperationRemind();
      Event.emit('getSystemInfo', global);
    });

  }

  componentDidShow () {
    this.checkStatusTimer = setInterval(async () => {
      this.checkOperationRemind();
      if (global.currentBindingVillage !== null) {
        await this.getSystemInfo(global.currentBindingVillage.villageId)
        Event.emit('getSystemInfo', global);
      }
    }, 5000)
  }

  componentDidHide () {
    if (this.checkStatusTimer) {
      clearInterval(this.checkStatusTimer)
    }
  }

  componentDidCatchError () {}

  /**
   * 获取登录code
   * @returns {Promise<string>}
   */
  async getLoginCode() {
    let loginRes = await Taro.login();
    if (!loginRes.code) {
      throw new Error('小程序Login接口异常');
    }
    return loginRes.code
  }

  /**
   * 检测注册登录状态
   * @returns {Promise<void>}
   */
  async checkRegisterInfo() {
    try {
      let registerInfo = await Request.get(`/wx/isRegister?code=${await this.getLoginCode()}`);
      if (registerInfo.data.code === 20401) {
        global.isRegister = false;
        throw new Error('尚未注册1')
      }
      global.isLogin = true;
      global.isRegister = true;
      // global.setToken(registerInfo.data.data.token);
      global.token =  registerInfo.data.data.token;
      global.userInfo = registerInfo.data.data.wxUser;
      Event.emit("loginFinish");
      // this.setState({
      //   userInfo: registerInfo.data.data.wxUser
      // })
      console.log('登录成功');
    } catch (e) {
      console.log(e)
    }
  }

  /**
   * 获取系统信息
   * @returns {JSX.Element}
   */
  async getSystemInfo(villageId) {
    let currentVillageId = global.userInfo.bindingVillageId;
    if (villageId) {
      currentVillageId = villageId;
    }
    try {
      let result = await Request.get(`/wx/getSystemInfo?villageId=${currentVillageId || ''}`);
      if (result.data.code !== 200) {
        throw new Error()
      }
      let {wxNews, wxNotices, wxBanners, version, userAgreement, privacyPolicy} = result.data.data;
      global.news = wxNews;
      global.notices = wxNotices;
      global.banners = wxBanners;
      global.version = version;
      global.userAgreement = userAgreement;
      global.privacyPolicy = privacyPolicy;
    } catch (e) {
      console.log(e, '获取系统信息异常')
    }
  }

  /**
   * 获取实时状态
   * @returns {JSX.Element}
   */
  async checkOperationRemind() {
    if (global.isLogin === false || global.userInfo == null || global.userInfo.userId == null) {
      return ;
    }
    try {
      console.log(global.currentBindingVillage)
      let result = await Request.get(`/wx/checkOperationRemind/${global.userInfo.userId}/${global.currentBindingVillage !== null ? global.currentBindingVillage.villageId : '1'}`);
      if (result.data.code !== 200) {
        throw new Error()
      }
      Event.emit('checkOperationRemind', result.data.data)
    } catch (e) {
      console.log(e, '检测实时动态异常')
    }
  }

  handleSafeAreaStyle(safeArea) {
    const { top, bottom, left, right, width, height } = safeArea;

    return {
      paddingTop: top,
      paddingBottom: bottom - height,
      paddingLeft: left,
      paddingRight: right - width
    }

  }

  initConfig() {
    const systemInfo = Taro.getSystemInfoSync();
    global.safeAreaStyle = this.handleSafeAreaStyle(systemInfo.safeArea);
    global.safePaddingTopStyle = {paddingTop: systemInfo.safeArea.top}
    global.systemInfo = systemInfo;
  }


  // this.props.children 是将要会渲染的页面
  render () {
    this.initConfig();
    return this.props.children;
  }
}

export default App
